﻿<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" />

	<title>相册</title>

	<link rel="stylesheet" href="/Web/css/common.css" />
	<link rel="stylesheet" href="/web/component/common/font-awesome.min.css">

	<script src="/web/js/jquery.351.min.js"></script>
	<script>
		(() =>
		{
			let t = new Date().getTime();
			document.write(`<script src="/web/js/common.js?t=${t}"><\/script>
							<script src="/web/js/form.js?t=${t}"><\/script>
							<script src="/web/js/upload.js?t=${t}"><\/script>
						`);
		})();
	</script>

	<style>
		div.dir { height: 35px; white-space: nowrap }
		div.container { height: calc(100% - 45px); margin: 5px auto auto auto; overflow: auto }

			div.container > div > div { float: left; width: 150px; height: 230px; margin-left: 10px; margin-top: 5px; border: solid 1px darkgray; text-align: center }

		div.image-cell { color: darkblue }
			div.image-cell > a { line-height: 0px; text-decoration: none }
				div.image-cell > a > div { width: 150px; height: 150px; display: table-cell; text-align: center; vertical-align: middle; border-bottom: solid 1px lightgray }
			div.image-cell > div { width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 15px; line-height: 35px }
				div.image-cell > div.change { cursor: pointer; border-bottom: 1px dashed skyblue }
			div.image-cell i.fa-folder { font-size: 100px; }
			div.image-cell i.count { font-size: 15px; color: green; }
			div.image-cell img { max-width: 150px; max-height: 150px }
			div.image-cell button { line-height: 35px; font-size: 25px }

		#tblList td { white-space: nowrap }
		#tblList button, div.container button { background-color: transparent; border: none }
		i.fa { color: blueviolet }
		i.fa-key, i.fa-power-off { font-size: 17px }
		i.fa-paste.disabled { color: darkgrey }
	</style>

	<script>
		var owner = -1, me, cutting;
		var inviewObserver;

		$(() =>
		{
			initVisibleObserver();
			listItems();
			webSocket();
		});

		function initVisibleObserver()
		{
			inviewObserver = new IntersectionObserver(entries =>
			{
				let imgs = entries.filter(en => en.isIntersecting).map(en => en.target);
				for (let img of imgs)
				{
					img.onload = evt =>
					{
						evt.target.removeAttribute("sc");
						inviewObserver.unobserve(evt.target);
					};

					img.setAttribute("src", img.getAttribute("sc"));
				}
			}, { root: $("div.container")[0] });
		}
	</script>

	<script>
		async function addDir()
		{
			let title = await prompt("目录名称", "新目录");
			if (title == undefined || title == null)
				return;
			else if ((title = title.trim()) == "")
				alert("目录名称不能为空或全空格");
			else
			{
				let form = new FormData();
				form.append("title", title);

				await request("新建目录", "CommonHDL.ashx?cmd=addDir", false, { method: "POST", body: form });
				await listItems();
			}
		}

		async function modDir(dir, name)
		{
			let title = prompt("目录名称", name);
			if (title == undefined || title == null)
				return;
			else if ((title = title.trim()) == "")
				alert("目录名称不能为空或全空格");
			else
			{
				let form = new FormData();
				form.append("dir", dir);
				form.append("title", title);

				await request("目录改名", "CommonHDL.ashx?cmd=modDir", true, { method: "POST", body: form });
				await listItems();
			}
		}

		async function delDir(dir)
		{
			if (!confirm("你确定执行删除目录操作吗？")) return;

			await request("删除目录", `CommonHDL.ashx?cmd=delDir&dir=${dir}`);
			await listItems();
		}

		async function listItems(skipUploadUI)
		{
			sessionStorage.setItem("owner", owner);
			let result = await request("列表", `mlist.ashx?cmd=list&owner=${owner}`);
			$("div.dir").html(result.path);

			if (result.me)
				$("div.container > div").html(`
<div class="image-cell">
	<a href="javascript:navigate('${me = result.me.id}')">
		<div style="line-height:185px;font-size:100px">
			<i class="fa fa-user"></i>
		</div>
	</a>
	<div>${result.me.name} <button onclick='psw("${result.me.id}")'><i class="fa fa-key"></i></button><button onclick="if(confirm('你要退出登录吗？')) location.href='login.htm'"><i class="fa fa-power-off"></i></button></div>
</div>`).append($("template-dir").html()).append(result.dirs.map(rec => `
<div class="image-cell">
	<a href="javascript:navigate('${rec.id}')">
		<div>
			<div><i class="fa fa-folder"></i></div>
			<i class="count">${rec.count}个文件</i>
		</div>
	</a>
	<div class="change" onclick="modDir('${rec.id}','${rec.name.replace(/"/g, '\\"').replace(/'/g, "\\'")}')">${rec.name}</div>
	<div><button onclick="delDir('${rec.id}')"><i class="fa fa-close"></i></button></div>
</div>`).join(""));
			else
			{
				inviewObserver.disconnect();

				let cells = result.map(rec => `
<div class="image-cell">
	<a href="view.htm?photo=${rec.id}&owner=${owner}" target="_blank">
		<div id="${rec.id}">
			<img src="/web/loading.gif" sc="${rec.thumb}" />
		</div>
	</a>
	<div title ${!rec.mine ? "" : `class="change" remark="${rec.remark == null ? "" : rec.remark.replace(/"/g, '\\"')}" onclick="modPhoto(this, '${rec.id}')"`}>${rec.remark == null ? rec.title : rec.remark}</div>
	${!rec.mine ? "" : `<div style="display:flex; justify-content: space-around"><button onclick="cut('${rec.id}')"><i class="fa fa-cut"></i></button><button onclick="delPhoto('${rec.id}')"><i class="fa fa-close"></i></button></div>`}
</div>`).join("");

				if (skipUploadUI)
					$("div.image-cell").remove();
				else
					$("div.container > div").html('<div style="font-size: 100px; line-height: 200px; cursor: pointer; text-align: center" onclick="goUpper()"><i class="fa fa-reply"></i></div>')
											.append(owner == me || owner == -1 ? "" : $("template-file").html());

				$("div.container > div").append(cells);

				$("img[sc]").each((_, elem) => inviewObserver.observe(elem));
			}

			if (cutting == undefined) $("i.fa-paste").addClass("disabled");
		}

		async function goUpper()
		{
			owner = 0;
			await listItems();
		}

		async function navigate(id)
		{
			owner = id;
			await listItems();
		}

		async function modPhoto(ctl, id)
		{
			let remark = prompt("图片备注", $(ctl).attr("remark"));
			if (remark == undefined) return; else remark = remark.trim();

			let form = new FormData();
			form.append("photo", id);
			form.append("remark", remark);

			await request("设置图片备注", "CommonHDL.ashx?cmd=modPhoto", true, { method: "POST", body: form });

			if (remark == "")
			{
				remark = $(ctl).attr("remark");
				$(ctl).removeAttr("remark");
			}
			else
				$(ctl).attr("remark", remark);
			$(ctl).html(remark).attr("title", remark)[0].onclick = () => modPhoto(ctl, id);
		}

		async function delPhoto(id)
		{
			if (!confirm("你确定要删除此图片吗？")) return;

			let form = new FormData();
			form.append("photo", id);
			await request("删除图片", "CommonHDL.ashx?cmd=delPhoto", true, { method: "POST", body: form });
			$(`div#${id}`).parents("div.image-cell").remove();
		}

		function updFile_change()
		{
			$("#lblUpload").html(event.target.files.length);
			Upload('updFile', me.id, progress, finish);
		}

		function progress(total, progress)
		{
			$("#progress").height(`${parseInt(100 * (total - progress) / total)}%`);
		}

		async function finish(serverFiles)
		{
			$("#updFile").replaceWith($("#updFile")[0].outerHTML);

			let form = new FormData();
			form.append("dir", owner);
			form.append("files", JSON.stringify(serverFiles));

			let callback = async ok =>
			{
				listItems(true);

				$("i.upload-tag").removeClass("fa-cloud-upload").addClass(ok ? "fa-check" : "fa-close");
				await sleep(2000);
				$("i.upload-tag").removeClass(ok ? "fa-check" : "fa-close").addClass("fa-cloud-upload");
				$("#progress").height("100%");
				$("#lblUpload").html("0");
			};

			await request("保存文件", "CommonHDL.ashx?cmd=saveUpload", false, { method: "POST", body: form })
				.then(() => callback(true))
				.catch(res =>
				{
					if (res.includes("以下文件未能保存")) callback(false);
				});
		}
	</script>

	<script>
		function cut(id)
		{
			cutting = id;
			$("i.fa-paste").removeClass("disabled");
			alert("记录已剪切，去到目标目录点击粘贴即可完成移动");
		}

		async function paste()
		{
			if (cutting == undefined) return;

			await request("移动", `CommonHDL.ashx?cmd=move&moved=${cutting}&to=${owner}`);
			cutting = undefined;
			$("i.fa-paste").addClass("disabled");
			await listItems();
		}
	</script>

	<script>
		function webSocket()
		{
			let ws = new WebSocket(`ws://${location.href.substr(7).split("/")[0]}/web/handler/websocket.ashx`);
			ws.onmessage = msg =>
			{
				let m = msg.data;
				let parts = m.split(":", 4);
				if (parts.length == 4 && parts[0] == "photo")
					switch (parts[2])
					{
						case "src":
							$(`div#${parts[1]} > img`).attr({ src: parts[3], sc: parts[3] });
							break;

						case "title":
							$(`div#${parts[1]}`).parents("div.image-cell").find("div[title]").attr({ title: parts[3], remark: parts[3] }).html(parts[3]);
							break;
					}
			}
		}
	</script>
</head>
<body class="no-select-text" style="overflow:hidden">

<div style="width: 98%; margin-left: auto; margin-right: auto; height:100%; overflow:hidden">
	<div class="dir" style="text-align:center;margin-top:5px;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;direction:rtl"></div>

	<div class="container">
		<div></div>
	</div>

<input type="file" id="updFile" multiple="multiple" accept="image/*" style="display:none" onchange="updFile_change()" />

<template-dir style="display:none">
	<div style="font-size: 60px; line-height: 230px; cursor:pointer; text-align:center" class="fa-stack" onclick="addDir()">
		<i class="fa fa-folder-o fa-2x" style="margin-top:50px"></i>
		<i class="fa fa-plus fa-stack-1x"></i>
	</div>
</template-dir>
<template-file>
	<div style="font-size: 100px; line-height: 230px; cursor:pointer; text-align:center; background-color:lightskyblue" onclick='$("#updFile")[0].click()'>
		<div style="width:100%; height:50px; margin-bottom:-50px; line-height:50px; font-size:15px">待上传<label id="lblUpload">0</label>个文件</div>
		<div style="height:100%; margin-bottom:-230px"><i class="fa fa-cloud-upload upload-tag"></i></div>
		<div id="progress" style="width:100%; height:100%; background-color:white"></div>
	</div>
	<div style="font-size: 100px; line-height: 230px; cursor:pointer; text-align:center" onclick="paste()">
		<i class="fa fa-paste"></i>
	</div>
</template-file>

</body>
</html>